<template>
  <view class="container">
    <view class="form-wrapper">
      <!-- 客户名称 -->
      <view class="form-item">
        <text class="label">客户名称</text>
        <view class="input readonly">{{ formData.customerName }}</view>
      </view>

      <!-- 可预约项目 -->
      <view class="form-item">
        <text class="label">可预约项目</text>
        <view v-if="isFromMyAppointment" class="input readonly">{{ itemProjectName }}</view>
        <picker v-else @change="handleProjectChange" :value="formData.projectIndex" :range="projectList" range-key="itemName">
          <view class="picker">
            {{ formData.projectIndex > -1 ? projectList[formData.projectIndex].itemName : '请选择预约项目' }}
            <text class="arrow">></text>
          </view>
        </picker>
      </view>

      <!-- 预约时间段 -->
      <view class="form-item">
        <text class="label">预约时间段</text>
        <view v-if="isFromMyAppointment" class="date-time-picker">
          <view class="date-picker readonly">{{ formData.date }}</view>
          <view class="time-picker readonly">{{ formData.time }}</view>
        </view>
        <view v-else class="date-time-picker">
          <picker mode="date" :value="formData.date" @change="handleDateChange">
            <view class="date-picker">
              {{ formData.date || '请选择日期' }}
              <text class="calendar-icon">📅</text>
            </view>
          </picker>
          <picker mode="time" :value="formData.time" start="09:00" end="18:00" @change="handleTimeChange">
            <view class="time-picker">
              {{ formData.time || '请选择时间' }}
              <text class="time-icon">🕒</text>
            </view>
          </picker>
        </view>
      </view>

      <!-- 预约门店 -->
      <view class="form-item">
        <text class="label">预约门店</text>
        <view class="input readonly">{{ formData.shopName }}</view>
      </view>

      <!-- 预约美导 -->
      <view class="form-item">
        <text class="label">预约美导</text>
        <view v-if="isFromMyAppointment" class="input readonly">{{ guideName }}</view>
        <picker v-else @change="handleBeauticianChange" :value="formData.guideIndex" :range="beauticianList" range-key="nickName">
          <view class="picker">
            {{ formData.guideIndex > -1 ? beauticianList[formData.guideIndex].nickName : '请选择美导' }}
            <text class="arrow">></text>
          </view>
        </picker>
      </view>
    </view>

    <!-- 按钮 -->
    <!-- <view v-if="isFromMyAppointment" class="delete-btn" @tap="handleDelete">删除预约</view> -->
    <view v-if="!isFromMyAppointment" class="submit-btn" @tap="handleSubmit">保存</view>

    <!-- 获取手机号组件 -->
    <get-phone-number v-model:show="showGetPhone" @success="onGetPhoneSuccess" @reject="onGetPhoneReject" />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { images } from '@/config/images';
import { getProjectList, getBeautician, submitAppointment, type AppointmentParams } from '@/api/store';
import GetPhoneNumber from '@/components/GetPhoneNumber.vue';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();

interface Project {
  id: number;
  itemName: string;
}

interface Beautician {
  userId: number;
  nickName: string;
}

interface FormData {
  customerName: string;
  projectIndex: number;
  date: string;
  time: string;
  shopName: string;
  id: number;
  guideName: string;
  guideIndex: number;
}

// 表单数据
const formData = ref<FormData>({
  customerName: '',
  projectIndex: -1,
  date: '',
  time: '',
  shopName: '',
  id: 0,
  guideName: '',
  guideIndex: -1,
});

const itemProjectName = ref('');
const guideName = ref('');

// 模拟数据
const projectList = ref<Project[]>([]);

// 获取项目列表
const getProjectItem = async () => {
  const res = await getProjectList();
  projectList.value = res.rows;
};

const beauticianList = ref<Beautician[]>([]);
// 获取美导列表
const getBeauticianItem = async () => {
  const res = await getBeautician();
  beauticianList.value = res.rows;
};

// 是否来自我的预约页面
const isFromMyAppointment = ref(false);

// 是否显示获取手机号弹窗
const showGetPhone = ref(false);

// 接收页面参数
onLoad((options: any) => {
  console.log('接收到的参数：', options);

  // 判断来源
  isFromMyAppointment.value = options.from === 'myAppointment';

  // 设置门店信息
  if (options.id && options.shopName) {
    formData.value.id = Number(options.id);
    formData.value.shopName = decodeURIComponent(options.shopName);
  }

  // 设置客户名称
  if (options.userName) {
    formData.value.customerName = decodeURIComponent(options.userName);
  }

  // 设置营业时间
  if (options.storeHours) {
    const [start, end] = decodeURIComponent(options.storeHours)
      .split('~')
      .map((t) => t.trim());
    formData.value.time = start;
  }

  if (options.itemProjectName) {
    itemProjectName.value = decodeURIComponent(options.itemProjectName);
  }

  if (options.guideName) {
    guideName.value = decodeURIComponent(options.guideName);
  }

  // 设置默认日期为今天
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  formData.value.date = `${year}-${month}-${day}`;
});

// 处理项目选择
const handleProjectChange = (e: any) => {
  formData.value.projectIndex = Number(e.detail.value);
};

// 处理日期选择
const handleDateChange = (e: any) => {
  formData.value.date = e.detail.value;
};

// 处理时间选择
const handleTimeChange = (e: any) => {
  formData.value.time = e.detail.value;
};

// 处理美导选择
const handleBeauticianChange = (e: any) => {
  formData.value.guideIndex = Number(e.detail.value);
  formData.value.guideName = beauticianList.value[formData.value.guideIndex].nickName;
};

// 提交表单
const handleSubmit = async () => {
  // 验证表单
  if (!formData.value.customerName) {
    uni.showToast({
      title: '请输入客户名称',
      icon: 'none',
    });
    return;
  }

  if (formData.value.projectIndex === -1) {
    uni.showToast({
      title: '请选择预约项目',
      icon: 'none',
    });
    return;
  }

  if (!formData.value.date || !formData.value.time) {
    uni.showToast({
      title: '请选择预约时间',
      icon: 'none',
    });
    return;
  }

  if (!formData.value.id) {
    uni.showToast({
      title: '请选择预约门店',
      icon: 'none',
    });
    return;
  }

  if (formData.value.guideIndex === -1) {
    uni.showToast({
      title: '请选择美导',
      icon: 'none',
    });
    return;
  }

  try {
    // 构建预约参数
    const params: AppointmentParams = {
      applyUserId: userStore.userInfo.user.userId,
      applyTime: `${formData.value.date} ${formData.value.time}:00`,
      applyConsultant: beauticianList.value[formData.value.guideIndex].userId,
      itemId: projectList.value[formData.value.projectIndex].id,
      shopId: formData.value.id,
      status: '10',
    };

    // 调用预约接口
    const res = await submitAppointment(params);

    if (res.code === 200) {
      uni.showToast({
        title: '预约成功',
        icon: 'success',
      });

      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({
        title: res.message || '预约失败',
        icon: 'none',
      });
    }
  } catch (error) {
    console.error('预约失败:', error);
    uni.showToast({
      title: '预约失败，请重试',
      icon: 'none',
    });
  }
};

// 删除预约
const handleDelete = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除此预约吗？',
    success: (res) => {
      if (res.confirm) {
        uni.showToast({
          title: '删除预约成功',
          icon: 'success',
          duration: 2000,
          success: () => {
            setTimeout(() => {
              uni.navigateBack();
            }, 2000);
          },
        });
      }
    },
  });
};

// 检查是否需要获取手机号
const checkNeedPhone = () => {
  const phone = uni.getStorageSync('userPhone');
  showGetPhone.value = !phone;
  if (phone) {
    // 获取项目列表
    getProjectItem();

    // 获取美导列表
    getBeauticianItem();
  }
};

// 获取手机号成功回调
const onGetPhoneSuccess = (phone: string) => {
  // 获取项目列表
  getProjectItem();

  // 获取美导列表
  getBeauticianItem();
  userStore.fetchUserInfo();
  formData.value.customerName = userStore.userInfo.user.nickName;
};

// 获取手机号拒绝回调
const onGetPhoneReject = () => {
  // 用户拒绝授权，会自动返回上一页
  setTimeout(() => {
    uni.navigateBack();
  }, 1500);
};

// 页面加载时检查手机号
onMounted(() => {
  checkNeedPhone();
});
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  padding: 30rpx;
  background: #f5f5f5;
}

.form-wrapper {
  background: #fff;
  border-radius: 20rpx;
  padding: 20rpx;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1px solid #eee;

  .label {
    width: 180rpx;
    font-size: 28rpx;
    color: #333;
    flex-shrink: 0;
  }

  .input {
    flex: 1;
    height: 60rpx;
    font-size: 28rpx;
    background: #f8f9fc;
    border-radius: 8rpx;
    padding: 0 20rpx;
    line-height: 60rpx;
    width: 400rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    &.readonly {
      background: #f5f5f5;
      color: #666;
    }
  }

  .picker {
    flex: 1;
    height: 60rpx;
    line-height: 60rpx;
    font-size: 28rpx;
    color: #333;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #f8f9fc;
    border-radius: 8rpx;
    padding: 0 20rpx;

    .arrow {
      color: #999;
      margin-left: 10rpx;
    }
  }

  .date-time-picker {
    flex: 1;
    display: flex;
    gap: 20rpx;

    .date-picker,
    .time-picker {
      flex: 1;
      height: 60rpx;
      line-height: 60rpx;
      font-size: 28rpx;
      color: #333;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: #f8f9fc;
      border-radius: 8rpx;
      padding: 0 20rpx;

      .calendar-icon,
      .time-icon {
        margin-left: 10rpx;
        color: #999;
      }
    }
  }
}

.submit-btn {
  margin: 40rpx 30rpx;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background: rgb(58, 63, 157);
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
}

.delete-btn {
  margin: 40rpx 30rpx;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background: #ff4d4f;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
}
</style>
